const { classApi, classMemberApi } = require('../../../utils/api');

Page({
  data: {
    classId: null,
    className: '',
    classInfo: null,
    members: [],
    filteredMembers: [],
    loading: false,
    error: null,
    searchKeyword: '',
    currentFilter: 'all',
    statistics: {
      totalCount: 0,
      teacherCount: 0,
      studentCount: 0,
      parentCount: 0
    }
  },

  onLoad(options) {
    console.log('班级成员页面加载，参数:', options);
    
    const { classId, className } = options;
    if (!classId) {
      wx.showToast({
        title: '班级ID不能为空',
        icon: 'none'
      });
      wx.navigateBack();
      return;
    }
    
    this.setData({
      classId: parseInt(classId),
      className: decodeURIComponent(className || '')
    });
    
    this.loadClassMembers();
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadClassMembers();
  },

  // 加载班级成员信息
  async loadClassMembers() {
    this.setData({ loading: true, error: null });
    
    try {
      console.log('开始加载班级成员信息，班级ID:', this.data.classId);
      
      // 获取班级成员（新接口）
      const result = await classMemberApi.getClassMembers(this.data.classId);
      console.log('班级成员API响应:', result);
      
      // 处理新的API返回格式
      let members = [];
      if (result && result.code === 200) {
        members = result.data || [];
      } else if (result && Array.isArray(result)) {
        // 兼容旧格式
        members = result;
      } else if (result && result.data && Array.isArray(result.data)) {
        members = result.data;
      }
      
      const processedMembers = members.map(member => ({
        id: member.id,
        userId: member.id,
        name: member.nickname || '',
        nickname: member.nickname || '',
        phone: member.phone || '',
        identity: member.identity || '',
        avatar: member.avatarUrl || '',
        status: member.status || 1
      }));
      
      // 统计
      const statistics = {
        totalCount: processedMembers.length,
        teacherCount: processedMembers.filter(v=>v.identity==="老师").length,
        studentCount: processedMembers.filter(v=>v.identity==="学生").length,
        parentCount: processedMembers.filter(v=>v.identity==="家长").length
      };
      
      this.setData({
        members: processedMembers,
        filteredMembers: processedMembers,
        statistics,
        loading: false
      });
      this.applyFilter();
    } catch(error) {
      console.error('获取班级成员信息失败:', error);
      this.setData({ error: '加载失败，请重试', loading: false });
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.applyFilter();
  },

  // 清除搜索
  clearSearch() {
    this.setData({ searchKeyword: '' });
    this.applyFilter();
  },

  // 筛选切换
  onFilterChange(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({ currentFilter: filter });
    this.applyFilter();
  },

  // 应用筛选
  applyFilter() {
    const { members, searchKeyword, currentFilter } = this.data;
    let filtered = [...members];

    // 搜索筛选
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filtered = filtered.filter(member => 
        (member.nickname || member.name || '').toLowerCase().includes(keyword) ||
        (member.phone || '').includes(keyword) ||
        (member.identity || '').toLowerCase().includes(keyword)
      );
    }

    // 身份筛选
    if (currentFilter === 'teacher') {
      filtered = filtered.filter(member => member.identity === '老师');
    } else if (currentFilter === 'student') {
      filtered = filtered.filter(member => member.identity === '学生');
    } else if (currentFilter === 'parent') {
      filtered = filtered.filter(member => member.identity === '家长');
    }

    // 按身份排序
    filtered.sort((a, b) => {
      const order = { '老师': 1, '学生': 2, '家长': 3 };
      return (order[a.identity] || 4) - (order[b.identity] || 4);
    });

    this.setData({ filteredMembers: filtered });
  },

  // 点击成员项
  onMemberTap(e) {
    const member = e.currentTarget.dataset.member;
    console.log('点击成员:', member);
    
    // 显示成员详情
    wx.showModal({
      title: member.nickname || member.name || '未知用户',
      content: `身份：${member.identity || '未知'}\n手机：${member.phone || '未设置'}\n状态：${member.status === 1 ? '正常' : '禁用'}`,
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 联系成员
  contactMember(e) {
    const member = e.currentTarget.dataset.member;
    console.log('联系成员:', member);
    
    if (member.phone) {
      wx.showModal({
        title: '联系成员',
        content: `是否拨打 ${member.phone}？`,
        success: (res) => {
          if (res.confirm) {
            wx.makePhoneCall({
              phoneNumber: member.phone
            });
          }
        }
      });
    } else {
      wx.showToast({
        title: '该成员未设置手机号',
        icon: 'none'
      });
    }
  },

  // 发送消息
  sendMessage(e) {
    const member = e.currentTarget.dataset.member;
    console.log('发送消息给成员:', member);
    
    wx.showToast({
      title: '消息功能开发中',
      icon: 'none'
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadClassMembers().then(() => {
      wx.stopPullDownRefresh();
    });
  },

});

